<?php
class Pageley_Commerce_AuthenticationFilter implements Pageley_Controller_Filter {
    private $authenticationRequiredMessage = "common.authenticationRequired";
    private $authenticationView = "login";
    
    private $restrictedParameters;
    
    public function __construct() {
        $this->restrictedParameters = new Pageley_Util_ArrayMap();
        $this->restrictedParameters->add("^PHPSESSID$");
        $this->restrictedParameters->add("^.*_.*$");
        $this->restrictedParameters->add("^system\\.resourceLocation$");
        $this->restrictedParameters->add("^system\\.classLocation$");
    }
    
    public function doFilter($parameters) {
        $factory = Pageley_Controller_Session_Factory::getInstance();
        $session = $factory->getSession();
        $modelAndView = null;
        if($session->get(Pageley_Commerce_Session::CUSTOMER) === null) {
            $model = new Pageley_Util_ArrayMap();
            $model->put("messages", new Pageley_Util_ArrayMap(
                new Pageley_I18n_Message($this->authenticationRequiredMessage)));
            $model->put("targetPage.location", $this->assembleUrl($parameters));
            $modelAndView = new Pageley_Controller_ModelAndView($model, $this->authenticationView);
        }
        return $modelAndView;
    }
    
    private function assembleUrl($parameters) {
        $url = "/dispatcher.php";
        $first = true;
        foreach($parameters as $key => $value) {
            $matches = false;
            foreach($this->restrictedParameters as $regex) {
                $pattern = new Pageley_Util_Pattern("@" . $regex . "@");
                if(!$pattern->match($key)->isEmpty()) {
                    $matches = true;
                    break;
                }
            }
            if(!$matches) {
                if($first) {
                    $url .= "?";
                    $first = false;
                } else {
                    $url .= "&";
                }
                $url .= $key . "=" . urlencode($value);
            }
        }
        return $url;
    }
    
    public function setAuthenticationRequiredMessage($authenticationRequiredMessage) {
        $this->authenticationRequiredMessage = $authenticationRequiredMessage;
    }
    
    public function setAuthenticationView($authenticationView) {
        $this->authenticationView = $authenticationView;
    }
}